﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace TimeProject.Validators.Utils
{
    internal static class StringUtil
    {
        /// <summary>
        /// Checks if the specified string is a well-formed e-mail address.
        /// </summary>
        /// <param name="s">The string to check.</param>
        /// <returns>True if the string is a well-formed e-maill address.</returns>
        public static bool IsWellFormedEmail(string s)
        {
            bool invalid = false;

            if (String.IsNullOrEmpty(s))
            {
                return false;
            }

            // Use IdnMapping class to convert Unicode domain names. 
            try
            {
                s = Regex.Replace(s, @"(@)(.+)$", delegate(Match match)
                {
                    IdnMapping idn = new IdnMapping();

                    string domainName = match.Groups[2].Value;
                    try
                    {
                        domainName = idn.GetAscii(domainName);
                    }
                    catch (ArgumentException)
                    {
                        invalid = true;
                    }
                    return match.Groups[1].Value + domainName;
                }, RegexOptions.None, TimeSpan.FromMilliseconds(200));
            }
            catch (RegexMatchTimeoutException)
            {
                return false;
            }

            if (invalid)
            {
                return false;
            }

            // Return true if strIn is in valid e-mail format. 
            try
            {
                return Regex.IsMatch(s,
                      @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                      RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
            }
            catch (RegexMatchTimeoutException)
            {
                return false;
            }
        }

    }
}
